package linker.list;

import linker.account.Account;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

/**
 * 
 * @version linker 0.93
 * @author Jianfeng jianfeng.linker@gmail.com
 * 
 */
public class FunctionItem extends DefaultListItem {

	private String title;

	private String command;

	private JPopupMenu lastMenu;

	private FunctionItem functionItem;

	public FunctionItem(String title, String command) {

		setTitle(title);
		setCommand(command);
		functionItem = this;
	}

	public void setCommand(String command) {
		this.command = command;
	}

	public String getTitle() {
		return title;
	}

	public String getCommand() {
		return command;
	}

	public String toString() {
		return title;
	}

	public void doubleClick() {
		try {
			Runtime.getRuntime().exec(command);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public ActionListener getActionListener() {
		ActionListener listener;

		listener = new ActionListener() {

			public void actionPerformed(ActionEvent e) {

				if (e.getActionCommand() == "Edit") {

					new FunctionEdit(functionItem);

					lastMenu.setVisible(false);
					lastMenu = null;
				} else if (e.getActionCommand() == "delete") {

				}
			}
		};

		return listener;
	}

	public JPopupMenu getPopupMenu() {
		JPopupMenu menu = new JPopupMenu();

		JMenuItem item = new JMenuItem("Edit");
		item.addActionListener(getActionListener());
		menu.add(item);
		item = new JMenuItem("Delete");
		item.addActionListener(getActionListener());
		menu.add(item);

		lastMenu = menu;
		return menu;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setTitleAndCommand(String title, String command) {
		Account.getFunctionList().save(this.title, title, command);
		setTitle(title);
		setCommand(command);
	}

	public void leftClick() {
		try {
			Runtime.getRuntime().exec(command);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
